<template>
  <div>
    <!-- 面包屑导航区 -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>用户管理</el-breadcrumb-item>
      <el-breadcrumb-item>用户列表</el-breadcrumb-item>
    </el-breadcrumb>

    <!-- 卡片视图区 -->
    <el-card>
      <!-- 搜索与添加区域 -->
      <el-row :gutter="20">
        <el-col :span="8">
          <el-input placeholder="请输入内容" v-model="queryInfo.username" clearable @clear="getUserList">
            <el-button slot="append" icon="el-icon-search" @click="getUserList"></el-button>
          </el-input>
        </el-col>
        <el-col :span="4">
          <el-button type="primary" @click="dialogVisible = true">添加用户</el-button>
        </el-col>
      </el-row>

      <!-- 用户列表区域 -->
      <el-table :data="userList" border stripe>
        <el-table-column type="index"></el-table-column>
        <el-table-column label="姓名" prop="username"></el-table-column>
        <el-table-column label="密码" prop="password"></el-table-column>
        <el-table-column label="角色" prop="roleName"></el-table-column>
        <el-table-column label="状态">
          <template slot-scope="scope">
            <el-switch v-model="scope.row.userStatus" :active-value="0" :inactive-value="1"
                       @change="userStatusChange(scope.row)">
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column label="操作">
          <template slot-scope="scope">
            <!-- 修改按钮 -->
            <el-button type="primary" icon="el-icon-edit" size="mini"
                       @click="editUserShowDialog(scope.row.id)"></el-button>
            <!-- 删除按钮 -->
            <el-button type="danger" icon="el-icon-delete" size="mini"
                       @click="removeUserById(scope.row.id)"></el-button>
            <!-- 分配角色按钮 -->
            <el-tooltip class="item" effect="dark" content="分配角色" placement="top" :enterable="false">
              <el-button type="warning" icon="el-icon-setting" size="mini" @click="setRoleShowClick(scope.row)"></el-button>
            </el-tooltip>
          </template>
        </el-table-column>
      </el-table>

      <!-- 分页信息区域 -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pageNum"
        :page-sizes="[5, 10, 15, 20]"
        :page-size="queryInfo.pageSize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>

    </el-card>

    <!-- 添加用户的对话框 -->
    <el-dialog
      title="新增"
      :visible.sync="dialogVisible"
      width="50%"
      :before-close="handleClose"
      @close="addDialogClosed">

      <!-- 用户的表单 -->
      <el-form :model="addForm" :rules="addFormRules" ref="addFormRef" label-width="110px"
               :label-position="labelPosition">
        <el-form-item label="用户名" prop="username">
          <el-input v-model="addForm.username"></el-input>
        </el-form-item>

        <el-form-item label="密码" prop="password">
          <el-input v-model="addForm.password" show-password></el-input>
        </el-form-item>

        <el-form-item label="再次输入密码" prop="password2">
          <el-input v-model="addForm.password2" show-password></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
              <el-button @click="dialogVisible = false">取 消</el-button>
              <el-button type="primary" @click="addUser">确 定</el-button>
            </span>
    </el-dialog>

    <!-- 修改用户信息的弹框 -->
    <el-dialog
      title="修改"
      :visible.sync="editUserDialogVisible"
      width="50%">

      <el-form ref="editFormRef" :model="editForm" label-width="100px" :rules="editFormRules">
        <el-form-item label="用户名：">
          <el-input v-model="editForm.username" disabled></el-input>
        </el-form-item>

        <el-form-item label="密码：">
          <el-input v-model="editForm.password"></el-input>
        </el-form-item>
      </el-form>

      <span slot="footer" class="dialog-footer">
        <el-button @click="editUserDialogVisible = false" @close="editDialogClosed">取 消</el-button>
        <el-button type="primary" @click="editUserInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 分配角色的Dialog -->
    <el-dialog
      title="分配角色"
      :visible.sync="allotDialogVisible"
      width="30%"
      @close="allotDialogClose">
      <div>
        <p>当前的用户：{{userInfo.username}}</p>
        <p>当前的角色：{{userInfo.roleName}}</p>
        <p>
          分配新角色：
          <el-select v-model="selectRoleId" placeholder="请选择">
            <el-option
              v-for="item in roleList"
              :key="item.id"
              :label="item.roleName"
              :value="item.id">
            </el-option>
          </el-select>
        </p>
      </div>
      <span slot="footer" class="dialog-footer">
        <el-button @click="allotDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="saveAllotDialogClick">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name: "Users",

  data() {
    // 验证二次输入的密码
    var checkPassword2 = (rule, value, callback) => {
      if (this.addForm.password === value) return callback();
      callback(new Error('两次输入的密码不相同！'));
    };

    return {
      // 获取用户列表的参数
      queryInfo: {
        'username': '',
        // 当前的页数
        'pageNum': 1,
        // 当前每页显示多少条数据
        'pageSize': 5
      },

      userList: [],

      // 数据总数
      total: 0,

      // 控制添加用户对话框的显示与隐藏
      dialogVisible: false,

      // 添加用户的表单数据
      addForm: {
        username: '',
        password: '',
        password2: ''
      },

      // 添加表单的验证规则对象
      addFormRules: {
        username: [
          {
            required: true, message: '请输入用户名', trigger: 'blur'
          },
          {
            min: 3, max: 10, message: '用户名的长度在 3 到 10 个字符之间！'
          }
        ],
        password: [
          {
            required: true, message: '请输入密码', trigger: 'blur'
          },
          {
            min: 6, max: 8, message: '密码长度在 6 到 8 位', trigger: 'blur'
          }
        ],
        password2: [
          {
            required: true, message: '再次输入密码不能为空', trigger: 'blur'
          },
          {
            min: 6, max: 8, message: '密码长度在 6 到 8 位', trigger: 'blur'
          },
          {
            validator: checkPassword2, trigger: 'blur'
          },
        ]
      },

      labelPosition: 'left',

      // 用于控制修改用户信息页面的展示与隐藏
      editUserDialogVisible: false,

      editForm: {},

      // 修改表单的验证规则
      editFormRules: {
        password: [
          {
            required: true, message: '请输入密码', trigger: 'blur'
          },
          {
            min: 6, max: 8, message: '密码长度在 6 到 8 位', trigger: 'blur'
          }
        ]
      },

      // 分配角色的Dialog 展示与否
      allotDialogVisible: false,
      // 需要被分配角色的用户信息
      userInfo: {},
      // 所有角色的列表
      roleList: [],
      // 下拉框选中的Id
      selectRoleId: ''
    }
  },

  created() {
    this.getUserList();
  },

  methods: {

    async getUserList() {
      const {data: res} = await this.$http.get('users', {params: this.queryInfo});
      console.log("data==", res.data);
      this.userList = res.data.userList;
      this.total = res.data.total;
    },

    // 监听 pageSize 改变的事件
    handleSizeChange(newSize) {
      this.queryInfo.pageSize = newSize;
      this.getUserList();
    },

    // 监听 页码值 改变的事件
    handleCurrentChange(newPage) {
      this.queryInfo.pageNum = newPage;
      this.getUserList();
    },

    // 监听switch开关的变化
    async userStatusChange(userInfo) {
      let userStatusFlag = true;
      if (userInfo.userStatus == 1) {
        userStatusFlag = false;
      }

      let putData = {'id': userInfo.id, 'userStatus': userInfo.userStatus}
      const {data: res} = await this.$http.put("users/state", putData);
      if (!res.status) {
        if (userStatusFlag) {
          userInfo.userStatus = 1;
        } else {
          userInfo.userStatus = 0;
        }
        return this.$message.error(res.message);
      }
      this.$message.success(res.message);
    },

    handleClose(done) {
      this.$confirm('确认关闭？')
        .then(_ => {
          done();
        })
        .catch(_ => {
        });
    },

    // 点击按钮,添加新用户
    addUser() {
      this.$refs.addFormRef.validate(async valid => {
        if (!valid) return;
        // 可以发起网络请求
        const {data: res} = await this.$http.post('users/add', this.addForm);
        if (!res.status) return this.$message.error(res.message);
        this.$message.success(res.message);
        // 隐藏添加用户对话框
        this.dialogVisible = false;
        // 刷新用户列表
        await this.getUserList();
        // 清空添加用户的表单
        this.addDialogClosed();
      });
    },

    // 监听添加用户对话框的关闭事件
    addDialogClosed() {
      this.$refs.addFormRef.resetFields();
    },

    // 控制修改用户弹窗隐藏还是展示
    async editUserShowDialog(id) {
      const {data: res} = await this.$http.get('/users/getUserById?id=' + id);
      if (!res.status) return this.$message.error(res.message);
      this.editForm = res.data;
      this.editUserDialogVisible = true;
    },

    // 监听修改用户对话框的关闭事件
    editDialogClosed() {
      this.$refs.editFormRef.resetFields();
    },

    // 修改用户信息，并提交
    editUserInfo() {
      this.$refs.editFormRef.validate(async valid => {
        console.log(valid);
        if (!valid) return;
        // 发起修改用户信息的数据请求
        const {data: res} = await this.$http.put("/users/edit",
          {'id': this.editForm.id, 'password': this.editForm.password});

        if (!res.status) return this.$message.error(res.message);

        // 关闭对话框
        this.editUserDialogVisible = false;
        // 刷新数据列表
        await this.getUserList();
        // 提示修改成功
        this.$message.success(res.message);
      })
    },

    // 根据Id删除对应的信息
    async removeUserById(id) {
      // 询问用户是否删除
      const confirmResult = await this.$confirm('此操作将永久删除改用户，是否继续？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch(err => err);

      // 如果用户确认删除，返回值为字符串 confirm, 点击取消，返回值为字符串 ‘cancel’
      if (confirmResult != 'confirm') {
        return this.$message.info('已经取消删除');
      }

      const {data: res} = await this.$http.delete('/users/del?id=' + id);

      if (!res.status) return this.$message.error(res.message);

      this.$message.success(res.message);
      await this.getUserList();
    },
    // 分配角色展示点击
    async setRoleShowClick (row) {
      this.userInfo = row;

      // 在展示对话框之前获取所有的角色列表
      const {data: res} = await this.$http.get('/role/getAllRoleList');

      if(!res.status) return this.$message.error(res.message);
      console.log("-=-=-=",res.data)
      this.roleList = res.data;
      this.allotDialogVisible = true;
    },
    // 分配角色页面确认按钮
    async saveAllotDialogClick() {
      if (!this.selectRoleId) return this.$message.error("请选择分配的角色");

      const {data: res} = await this.$http.put(`/role/${this.userInfo.id}/update`, {
        'roleId': this.selectRoleId
      })

      await this.getUserList();
      this.allotDialogVisible = false
    },
    // 分配角色弹框关闭事件
    allotDialogClose() {
      this.selectRoleId = '';
      this.userInfo = {};
    }

  }

}
</script>

<style lang="less" scoped>

</style>
